#include <bits/stdc++.h>

using namespace std;

class Solution {
   public:
    int find(int x, vector<int>& parent) {
        if (parent[x] != x) {
            parent[x] = find(parent[x], parent);
        }
        return parent[x];
    }
    long long countPairs(int n, vector<vector<int>>& edges) {
        vector<int> parent(n);
        vector<int> size(n);
        for (auto i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        for (auto edge : edges) {
            int i = find(edge[0], parent);
            int j = find(edge[1], parent);
            if (i != j) {
                if (size[i] > size[j]) {
                    parent[j] = i;
                    size[i] += size[j];
                } else {
                    parent[i] = j;
                    size[j] += size[i];
                }
            }
        }

        long long ret = 0;
        for (int i = 0; i < n; i++) {
            ret += n - size[find(i, parent)];
        }
        return ret / 2;
    }
};